﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using NL.ADA.ConfigService.DAL.EntityClasses;
using NL.ADA.ConfigService.DAL.DatabaseSpecific;
using NL.ADA.ConfigService.DAL.FactoryClasses;
using NL.ADA.ConfigService.DAL.HelperClasses;
using NL.ADA.ConfigService.DAL.RelationClasses;
using NL.ADA.ConfigService.DAL.TypedListClasses;
using NL.ADA.ConfigService.DAL;
using SD.LLBLGen.Pro.ORMSupportClasses;
using NL.ADA.Common;
using System.ServiceModel;

namespace NL.ADA.ConfigAdmin
{
    public class ConfigManager : ManagerBase<ConfigEntity>
    {
        public ConfigManager()
        {

        }


        public override int Insert(ConfigEntity entity)
        {
            var insertResult = base.Insert(entity);
            try
            {
                using (var adapter = new DataAccessAdapter())
                {
                    adapter.FetchEntity(entity);
                }

                var modifiedEntity = new ApplicationModeModifiedEntity(entity.ApplicationId, entity.ModeId);

                using (var adapter = new DataAccessAdapter())
                {
                    var tempDate = DateTime.Now;

                    adapter.FetchEntity(modifiedEntity);
                    modifiedEntity.Modified = tempDate;
                    if (adapter.SaveEntity(modifiedEntity))
                    {
                        var callBack = new ImplementationCallback();
                        var context = new InstanceContext(callBack);
                        var notification = new NL.ADA.ConfigAdmin.NotificationServiceReference.NotificationServiceClient(context);

                        if (notification.State != CommunicationState.Opened)
                        {
                            Debug.WriteLine("-------------notificationstate is open ");
                            notification.Open();

                        }
                        Debug.WriteLine("-------------test before notification invocation");
                        Debug.WriteLineIf(notification.InnerDuplexChannel.OutputSession != null, "output session is not null");

                        if (notification.InnerDuplexChannel.InputSession != null)
                        {
                            Debug.WriteLine("-------------input session not null");
                            notification.NotifyServerModified(tempDate);
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {

            }
            return insertResult;
        }

        public override int Update(ConfigEntity entity)
        {

            var updateResult = base.Update(entity);

            try
            {
                using (var adapter = new DataAccessAdapter())
                {
                    adapter.FetchEntity(entity);
                }

                var modifiedEntity = new ApplicationModeModifiedEntity(entity.ApplicationId, entity.ModeId);
                using (var adapter = new DataAccessAdapter())
                {
                    var tempDate = DateTime.Now;
                    adapter.FetchEntity(modifiedEntity);
                    modifiedEntity.Modified = tempDate;
                    if (adapter.SaveEntity(modifiedEntity))
                    {
                        var callBack = new ImplementationCallback();
                        var context = new InstanceContext(callBack);
                        var notification = new NL.ADA.ConfigAdmin.NotificationServiceReference.NotificationServiceClient(context);
                        if (notification.State != CommunicationState.Opened)
                        {
                            notification.Open();

                        }
                        Debug.WriteLine("-------------test before notification invocation");
                        notification.NotifyServerModified(tempDate);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return updateResult;

        }
        //public virtual EntityCollection<ConfigEntity> Get()
        //{
        //    EntityCollection<ConfigEntity> result = new EntityCollection<ConfigEntity>();
        //    try
        //    {
        //        using (DataAccessAdapter adapter = new DataAccessAdapter())
        //        {
        //            adapter.FetchEntityCollection(result, null);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    return result;
        //}
        //public virtual EntityCollection<ConfigEntity> GetConfigByKey(string key, int appId)
        //{
        //    var result = new EntityCollection<ConfigEntity>();
        //    IRelationPredicateBucket bucket = new RelationPredicateBucket(ConfigFields.Key == key);
        //    bucket.PredicateExpression.AddWithAnd(ConfigFields.ApplicationId == appId);
        //    try
        //    {
        //        using (DataAccessAdapter adapter = new DataAccessAdapter())
        //        {
        //            adapter.FetchEntityCollection(result, bucket);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    return result;

        //}

        public virtual ConfigEntity GetConfigByKey(string key, int appId, int modeId)
        {
            var result = new ConfigEntity();
            result.Key = key;
            result.ApplicationId = appId;
            result.ModeId = modeId;

            try
            {
                using (var adapter = new DataAccessAdapter())
                {
                    if (!(adapter.FetchEntityUsingUniqueConstraint(result, result.ConstructFilterForUCKeyModeIdApplicationId())))
                    {
                        result = new ConfigEntity();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;

        }
        //public virtual string GetConfigValueByKey(string key, int appId, int modeId)
        //{
        //    var result = new ConfigEntity();
        //    IRelationPredicateBucket bucket = new RelationPredicateBucket(ConfigFields.Key == key);
        //    bucket.PredicateExpression.AddWithAnd(ConfigFields.ApplicationId == appId);
        //    bucket.PredicateExpression.AddWithAnd(ConfigFields.ModeId == modeId);
        //    try
        //    {
        //        using (DataAccessAdapter adapter = new DataAccessAdapter())
        //        {
        //            adapter.FetchEntity(result);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    return result.Value;

        //}

        public CustomConfigList GetAllConfigs(int appId, int modeId)
        {
            var result = new CustomConfigList();
            SelectAllConfigTypedList list = new SelectAllConfigTypedList();
            IPredicateExpression bucket = new PredicateExpression();

            if (appId > 0)
            {
                bucket.Add(ConfigFields.ApplicationId == appId);
            }

            if (modeId > 0)
            {
                bucket.Add(ConfigFields.ModeId == modeId);
            }

            using (DataAccessAdapter adapter = new DataAccessAdapter())
            {
                adapter.FetchTypedList(list, bucket);
            }

            foreach (SelectAllConfigRow row in list)
            {
                var customConfig = new CustomConfig();
                customConfig.ConfigId = row.ConfigId;
                customConfig.ApplicationId = row.ApplicationId;
                customConfig.ApplicationCode = row.AppCode;
                customConfig.ConfigTypeId = row.ConfigTypeId;
                customConfig.ConfigTypeName = row.ConfigTypeName;
                customConfig.Key = row.Key;
                customConfig.Value = row.Value;
                customConfig.ModeName = row.ModeName;
                customConfig.ModeId = row.ModeId;
                result.Add(customConfig);
            }
            return result;
        }

    }
}
